const jwt = require('jsonwebtoken');
const Users = require("../models/Users")
const passwordEncrypt = require('../utils/passwordEncrypt');
const randomTokenGen = require('../utils/generateToken');
const incID = require('../functions/incID');
const { getUser } = require('../services/userServices');
const bcrypt = require("bcryptjs")
const axios = require("axios");
const TokenWXs = require('../models/TokenWXs')


const registerUser = async (req, res) => {

    try {
        const usernameExist = await Users.findOne({ user_name: req.body.user_name });
        const emailExist = await Users.findOne({ email: req.body.email });

        if (usernameExist) {
            return res.status(400).json({ error_msg: '账号已注册' });
        }
        if (emailExist) {
            return res.status(400).json({ error_msg: '邮箱已绑定' });
        }
        req.body.id_user = await incID("user");
        req.body.login_ip = req.ip
        req.body.password = await passwordEncrypt(req.body.password);
        const savedUser = await Users(req.body).save();
        const token = await randomTokenGen(savedUser);
        if (!token) {
            res.status(500).json({ error_msg: '错误' });
        }
        return res.status(201).json({ data: savedUser });
    }
    catch (err) {
        console.log({ err });
        return res.status(400).json({ error_msg: err.message });
    }
}

const loginUser = async (req, res) => {
    try {
        const user = await getUser({ user_name: req.body.user_name });
        const validPass = await bcrypt.compare(req.body.password, user.password);
        if (!validPass) {
            return res.status(400).json({ error_msg: '密码错误' });
        }
        const token = jwt.sign(
            { _id: user._id, role: user.role },
            'This is the key and hello world'
        );
        return res.status(200).json({ access_token: token });
    }
    catch (err) {
        console.log({ err });
        return res.status(400).json({ error_msg: err.message });
    }
}


const loginByWX = async (req, res) => {
    try {
        console.log(req.body.code)
        let appid = "wx9d08284632afafe2"
        let secret = "44672f74531fad22be666f8e37c0a460"
        let code = req.body.code
        let geturl = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
        const wxdataget = await axios({
            url: geturl,
            method: "get"
        })
        var datasaved = {}
        console.log(wxdataget.data)

        const finduserbyopenid = await Users.findOne({ openid: wxdataget.data.openid })
        if (finduserbyopenid) {
            finduserbyopenid.session_key = wxdataget.data.session_key
            datasaved = await finduserbyopenid.save()
        } else {
            wxdataget.data.id_user = await incID("user");
            datasaved = await Users(wxdataget.data).save()
        }
        console.log(datasaved.role)

        const token = jwt.sign(
            { openid: wxdataget.data.openid, session_key: wxdataget.data.openid, role: datasaved.role,_id:datasaved._id },
            'This is the key and hello world'
        );

        const findtoken = await TokenWXs.findOne({ id_user: datasaved._id })
        if (findtoken) {
            findtoken.token = token
            await findtoken.save()
        } else {
            await TokenWXs({ token: token, id_user: datasaved._id }).save()
        }



        return res.status(200).json({ success: token });

    }
    catch (err) {
        console.log({ err });
        return res.status(400).json({ error_msg: err.message });
    }
}


module.exports = { registerUser, loginUser, loginByWX };